from django.db import models
from django.utils import timezone #为Python提供时区的定义并且SQLite也需要它来对日期进行操作
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from taggit.managers import TaggableManager


class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager,
                self).get_queryset().filter(status='published')


class Post(models.Model):
    '''帖子的主题内容'''
    #状态选择
    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Published'),
    )
    #标题
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250,
                            unique_for_date='publish')
    #文章作者，与用户绑定
    author = models.ForeignKey(User,
                                related_name='blog_posts')
    #文章主题
    body = models.TextField()
    #发布时间
    publish = models.DateTimeField(default=timezone.now)
    #创建时间
    created = models.DateTimeField(auto_now_add=True)
    #更新时间
    updated = models.DateTimeField(auto_now=True)
    #文章状态
    status = models.CharField(max_length=10,
                                choices=STATUS_CHOICES,
                                default='draft')
    objects = models.Manager()      #The default manager
    published = PublishedManager()  #Our custom manager
    tags = TaggableManager()        #提供 TaggableManager 管理器，允许给Post对象添加，获取以及移除标签。

#已发布时间倒序排列
    class Meta:
        ordering = ('-publish',)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('blog:post_detail',
                        args=[self.publish.year,
                                self.publish.strftime('%m'),
                                self.publish.strftime('%d'),
                                self.slug])


class Comment(models.Model):
    #通过外键将帖子和评论关联
    post = models.ForeignKey(Post, related_name='comments')
    name = models.CharField(max_length=80)
    email = models.EmailField()
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=True)

    class Meta:
        ordering = ('created',)

    def __str__(self):
        return 'Comment by {} on {}'.format(self.name, self.post)
